//
//  VOLChatViewController.m
//  Volver
//
//  Created by administrator on 14-10-21.
//  Copyright (c) 2014年 vol. All rights reserved.
//


#import "VOLChatViewController.h"
#import "common.h"
#import "VOLAppDelegate.h"
#import "VOLChatUser.h"
#import "FMDatabase.h"
#import "MessageModel.h"
#import "CellFrameModel.h"
#import "MessageCell.h"

#import "ASIHTTPRequest.h"
#import "ASIFormDataRequest.h"
#import "JSONKit.h"

#define kDBPath @"volTalk.sqlite"
#define kToolBarH 44
#define kTextFieldH 30
@interface VOLChatViewController ()
{
    XMPPStream *xmppstream;
    VOLAppDelegate *del ;
    NSMutableArray  *messagearray;
    XMPPRoster *roster;
    XMPPRosterCoreDataStorage *xmpprosterdatastorge;
    NSString *msg ;
    int i ;
    int isFirst ;//判断是否是第一次打开该页面
    VOLChatUser *chatuser ;
    JSONDecoder *json ;
}
@end

@implementation VOLChatViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    
    //设置代理
    self.tableview.delegate = self ;
    self.tableview.dataSource = self ;
    self.chatfield.delegate = self ;
    json = [[JSONDecoder alloc]init];
    
    
    //设置标题
    NSLog(@"%@",self.chatToName);
    
    //从账号解析初该用户的电话号码，再通过电话号码来查询该用户的name
    NSArray *phonearray = [self.chatToName componentsSeparatedByString:@"@"];
    NSString *phonenumber = [phonearray objectAtIndex:0];
    NSString *username =  [self getusername:phonenumber];
    self.title = [NSString stringWithFormat:@"正在和%@聊天",username] ;
    
    addBackButton() ;//返回按钮
    
    
    i= 0 ;//标记加好友的次输，初始为0，当加了一次好友后，不再执行加好友
    
    messagearray = [NSMutableArray array];//初始化聊天的消息数组
    
    del = kGetDel ;
    
    //初始化xmppstream
    xmppstream = [[XMPPStream alloc]init];
    xmppstream = del.xmppsteam ;
    roster = del.xmpproster ;
    
    //判断xmppstrem是否已经连接
    if ([xmppstream isConnected]) {
        NSLog(@"xmppstream已连接");
    }
    
    //当与我正在聊天的好友给我发来消息时,消息中心接受消息，给该页面加载该消息;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(update:) name:self.chatToName object:msg];
    
    //当聊天的人接收到消息时，把他的离线消息变为0
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(setOfflinemessage:) name:@"setofflinemessage" object:nil];
    
    [self loadmessage]; //从数据库里面加载数据
    
    self.tableview.separatorStyle = UITableViewCellSeparatorStyleNone; //设置分割线风格
    
    //设置背景色
    self.view.backgroundColor = [UIColor colorWithRed:235.0/255 green:235.0/255 blue:235.0/255 alpha:1.0];
    self.tableview.backgroundColor = [UIColor colorWithRed:235.0/255 green:235.0/255 blue:235.0/255 alpha:1.0];
    
    //默认为第一次打开该页面
    isFirst = 1 ;
    
    //如果该用户不是你的好友，则将该用户加为好友
    [self addnewuser];
    
    //将与你聊天的用户变为全局变量
    chatuser = [[VOLChatUser alloc]init];
    for ( VOLChatUser *user in del.rosters) {
        if ([self.chatToName isEqualToString: user.name]) {
            [self getUseHead:user];
            chatuser = user ;
        }
    }
    
    
    //刚进页面时，将该用户的离线消息设为0
    for (VOLChatUser *user in del.rosters) {
        
        if ([user.name isEqualToString:self.chatToName ]) {
            
            user.offlinemessage = 0  ;
            NSString *filename = [kGetDocumentsPath stringByAppendingPathComponent:@"offlinemessage.plist"];
            NSArray *array = [NSArray arrayWithObjects:user.name,[ NSNumber numberWithInteger:user.offlinemessage ] ,nil];
            
            [del.offlinemessagedic setObject:array forKey:user.name];
            
            if ([del.offlinemessagedic writeToFile:filename atomically:YES]) {
                NSLog(@"保存成功");
                
            }
        }
    }
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(hiddenkey)];
    [self.view addGestureRecognizer:tap];
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark 返回按钮事件
-(void)goBack:(id)sender{
    
    //返回时，将自己的离线消息数量设置为0，并保存到plist文件
    
    for (VOLChatUser *user in del.rosters) {
        
        if ([user.name isEqualToString:self.chatToName ]) {
            
            user.offlinemessage = 0  ;
            NSString *filename = [kGetDocumentsPath stringByAppendingPathComponent:@"offlinemessage.plist"];
            NSArray *array = [NSArray arrayWithObjects:user.name,[ NSNumber numberWithInteger:user.offlinemessage ] ,nil];
            
            [del.offlinemessagedic setObject:array forKey:user.name];
            
            if ([del.offlinemessagedic writeToFile:filename atomically:YES]) {
                NSLog(@"保存成功");
                
            }
        }
    }
    back;
}


#pragma mark- tableview代理方法
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [messagearray count];
}

#pragma mark - cellforrow
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    MessageCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (cell == nil) {
        cell = [[MessageCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }
    
    //通过messagemodel来设置聊天的边框
    CellFrameModel *cellframe = [[CellFrameModel alloc]init];
    [cellframe setMessage:[messagearray objectAtIndex:indexPath.row]];
    cell.user = chatuser ;
    cell.cellFrame = cellframe ;
    
    //如果是初次打开,则将tableview滚到倒数最后一行
    if (isFirst) {
        isFirst=0;
        //5.自动滚到最后一行
        NSIndexPath *lastPath = [NSIndexPath indexPathForRow:messagearray.count - 1 inSection:0];
        [self.tableview scrollToRowAtIndexPath:lastPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    }
    
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    
    return cell ;
    
}

#pragma mark-返回每一行的高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    //根据获得得messagemodel来设置每个cell的高度
    CellFrameModel *cellframe = [[CellFrameModel alloc]init];
    [cellframe setMessage:[messagearray objectAtIndex:indexPath.row]];
    return cellframe.cellHeght;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [self.tableview deselectRowAtIndexPath:indexPath animated:YES];
    
    [self.view endEditing:YES];
    [UIView animateWithDuration:0.3 delay:0 options:UIViewAnimationOptionLayoutSubviews animations:^{
        self.view.frame = CGRectMake(0, 0, 320, self.view.frame.size.height);
    } completion:^(BOOL finished) {
        NSLog(@"向上移动·");
    }];
    
}
#pragma mark- 发送消息
- (IBAction)sendmessage:(id)sender {
    [UIView animateWithDuration:0.3 delay:0 options:UIViewAnimationOptionLayoutSubviews animations:^{
        self.view.frame = CGRectMake(0, 0, 320, self.view.frame.size.height);
    } completion:^(BOOL finished) {
        NSLog(@"向上移动·");
    }];
    [self.view endEditing:YES];
    
    if (![self.chatfield.text isEqualToString:@""]) {
        
        
        //发送消息
        NSXMLElement *body = [NSXMLElement elementWithName:@"body"]; //消息的内容
        [body setStringValue:self.chatfield.text];
        
        
        NSXMLElement *message = [NSXMLElement elementWithName:@"message"];
        
        [message addAttributeWithName:@"type" stringValue:@"chat"]; //设置发送xml文件的类型
        
        NSString *to = self.chatToName ;
        [message addAttributeWithName:@"to" stringValue:to];//设置消息的发送对象
        [message addChild:body];
        
        [xmppstream sendElement:message]; // 发送消息
        
        //发送添加好友请求
        XMPPJID *jid = [XMPPJID jidWithString:self.chatToName];
        
        
        //[presence addAttributeWithName:@"subscription" stringValue:@"好友"];
        [roster subscribePresenceToUser:jid];
        
        
        // 将发送的消息添加至聊天内容数组
        NSString *time = [self getnowtime];
        MessageModel *tomg = [[MessageModel alloc]init];
        tomg.text = self.chatfield.text ;
        tomg.time = time ;
        tomg.type = kMessageModelTypeOther;
        tomg.showTime = YES ;
        [messagearray addObject:tomg];
        
        
        //将聊天输入框清空，刷新tableview；
        self.chatfield.text = @"";
        [self.tableview reloadData];
        
        
        //自动滚到最后一行
        NSIndexPath *lastPath = [NSIndexPath indexPathForRow:messagearray.count - 1 inSection:0];
        [self.tableview scrollToRowAtIndexPath:lastPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
        
        
        //如果该用户不是自己的好友，则将它加为好友
        [self addnewuser];
        
    }
    
}


#pragma mark -点击空白处位置复原
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    
    [self.view endEditing:YES];//取消键盘
    
    //向上移动
    [UIView animateWithDuration:0.3 delay:0 options:UIViewAnimationOptionLayoutSubviews animations:^{
        self.view.frame = CGRectMake(0, 0, 320, self.view.frame.size.height);
    } completion:^(BOOL finished) {
        NSLog(@"向上移动·");
    }];
    
}

#pragma mark- 阻止键盘遮挡
-(void)textFieldDidBeginEditing:(UITextField *)textField{
    textField.placeholder = @"";
    [UIView animateWithDuration:0.3 delay:0 options:UIViewAnimationOptionLayoutSubviews animations:^{
        self.view.frame = CGRectMake(0, -235, 320, self.view.frame.size.height);
    } completion:^(BOOL finished) {
        NSLog(@"向上移动·");
    }];
}


#pragma mark-消息中心传来消息,将受到的消息加入本页面的消息数组，再刷新数据

-(void)update:(NSNotification *)noticfication{
    NSString *msgs = [noticfication object];
    NSLog(@"------%@",msgs);
    
    
    NSString *time = [self getnowtime];
    MessageModel *message = [[MessageModel alloc]init];
    message.text = msgs ;
    message.time = time ;
    message.type =  kMessageModelTypeMe;
    message.showTime = YES ;
    [messagearray addObject:message];
    
    [self.tableview reloadData];
    
    
    NSIndexPath *lastPath = [NSIndexPath indexPathForRow:messagearray.count - 1 inSection:0];
    [self.tableview scrollToRowAtIndexPath:lastPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}


#pragma mark - 如果该用户不在用户数组，则将该用户加入用户数组
-(void) addnewuser{
    
    if (i ==0) {
        
        int flag = 0 ;
        for ( VOLChatUser *ur in del.rosters)
        {
            if ([ur.name isEqualToString:self.chatToName])
            {
                flag ++ ;
            }
        }
        
        
        if (flag == 0 )
        {
            VOLChatUser *user = [[VOLChatUser alloc]init];
            user.name = self.chatToName ;
            user.pearence = @"unavailable" ;
            [del.rosters addObject:user];
            [del getUseHead:user];
            i = 1 ;
        }
        
    }
    
    
}

#pragma mark - 创建数据库存储的路径
-(NSString *)getDBPath
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory=[paths objectAtIndex:0];//Documents目录
    return [NSString stringWithFormat:@"%@/message/%@",documentsDirectory,kDBPath];
}

#pragma mark- 加载数据库里面保存的与该用户的聊天记录
-(void) loadmessage{
    
    //获得自己的账号名
    NSString *prencefrom = xmppstream.myJID.description ;
    NSArray *array = [prencefrom componentsSeparatedByString:@"/"];
    NSString *myname = [array objectAtIndex:0];
    
    //读取数据库的内容
    FMDatabase *db = [FMDatabase databaseWithPath:[self getDBPath]];
    if ([db open])
    {
        NSString *sql = @"select * from talk" ; //查询数据库
        FMResultSet *rst =  [db executeQuery:sql]; //返回查询结果
        
        while ([rst next])
        {
            
            NSString *from = [rst stringForColumnIndex:1]; //消息的来源
            NSString *to = [rst stringForColumnIndex:2];    //消息的发送对象
            NSString *mesg = [rst stringForColumnIndex:3]; //消息的内容
            NSString *time = [rst stringForColumnIndex:4];  //发送消息的时间
            
            //如果消息的来源为自己且发送的对象为本页面的对象，则加载该消息，类型为我发给他
            if ([from isEqualToString:self.chatToName]&&[to isEqualToString:myname])
            {
                MessageModel *tomg = [[MessageModel alloc]init];
                tomg.text = mesg ;
                tomg.time = time ;
                tomg.type = kMessageModelTypeMe;
                tomg.showTime = YES ;
                [messagearray addObject:tomg];
            }
            
            //如果消息的来源为本页面的对象且发送的对象为自己，则加载该消息，类型他发给我
            else if ([from isEqualToString:myname]&&[to isEqualToString:self.chatToName])
            {
                MessageModel *Other = [[MessageModel alloc]init];
                Other.text = mesg ;
                Other.time = time ;
                Other.type = kMessageModelTypeOther;
                Other.showTime = YES ;
                [messagearray addObject:Other];
                
            }
            
        }
    }
    
}

#pragma mark-获取当前时间，并转化为指定的格式
-(NSString *) getnowtime{
    NSDate *chatdate = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyy年MM月dd日 H时K分ss秒"];
    NSString *messagetime = [formatter stringFromDate:chatdate];
    return messagetime ;
}

#pragma mark - 按enter键时，也发送消息
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self sendmessage:nil];
    return YES;
}

#pragma mark - 通过电话号码获取用户名
-(NSString *) getusername:(NSString *)phonenumber {
    
    NSString *urlString = [NSString stringWithFormat:@"%@user/getHeadByUserPhone?userPhone=%@",kHTTPHome,phonenumber];
    NSURL *url = [NSURL URLWithString:urlString];
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
    
    [request setRequestMethod:@"GET"];
    [request startSynchronous];
    
    
    NSData *data = [request responseData];
    NSString *username  = phonenumber ;
    
    
    if (data) {
        NSDictionary *dic = [json objectWithData:data];
        int status = [[dic objectForKey:@"status"] intValue];
        if (status == 1) {
            NSLog(@"success !!");
            
            NSArray *idhead = [dic objectForKey:@"idAndHead"];
            NSDictionary *k = [idhead objectAtIndex:0];
            username = [k objectForKey:@"user_name"];
            
        }
        
    }
    
    return username ;
}

#pragma mark 通过用户的号码来回去用户的id号和头像名
-(void)getUseHead:(VOLChatUser *)user
{
    
    //通过用户的账号名裁剪出手机号
    NSString *name = user.name ;
    NSArray *phonearray = [name componentsSeparatedByString:@"@"];
    NSString *phonenumbers= [phonearray objectAtIndex:0];
    
    
    //接口请求信息
    NSString *urlString = [NSString stringWithFormat:@"%@user/getHeadByUserPhone?userPhone=%@",kHTTPHome,phonenumbers];
    NSURL *url = [NSURL URLWithString:urlString];
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
    request.delegate = self ;
    [request setRequestMethod:@"GET"];
    [request startSynchronous];
    NSData *data = [request responseData];
    
    
    //如果返回成功，则将获得的信息赋值给user的属性
    if (data) {
        NSDictionary *dic = [json objectWithData:data];
        int status = [[dic objectForKey:@"status"] intValue];
        if (status == 1) {
            
            NSArray *idhead = [dic objectForKey:@"idAndHead"];
            NSDictionary *k = [idhead objectAtIndex:0];
            NSString *headname = [k objectForKey:@"user_head"];
            NSString *userid = [k objectForKey:@"user_id"];
            NSString *volname = [k objectForKey:@"user_name"];
            
            user.headname = headname ;
            user.userid = userid ;
            user.volname = volname ;
            
        }
        
        
    }
    
}

#pragma mark - 添加好友
-(void)adduser{
    
    int flag = 0 ;
    for ( VOLChatUser *ur in del.rosters)
    {
        
        if ([ur.name isEqualToString:self.chatToName])
        {
            flag ++ ;
            
        }
        
    }
    
    if (flag == 0 )
    {
        VOLChatUser *user = [[VOLChatUser alloc]init];
        if (user.name.length >13)
        {
            
            user.name = self.chatToName;
            user.pearence = @"unavailable" ;
            [del.rosters addObject:user];
            [self getUseHead:user];
        }
    }
    
}


#pragma amrk- 接收到正在聊天用户的消息，把他的离线消息设为0
-(void)setOfflinemessage:(id)sender{
    for (VOLChatUser *user in del.rosters) {
        
        if ([user.name isEqualToString:self.chatToName ]) {
            
            user.offlinemessage = 0  ;
            NSString *filename = [kGetDocumentsPath stringByAppendingPathComponent:@"offlinemessage.plist"];
            NSArray *array = [NSArray arrayWithObjects:user.name,[ NSNumber numberWithInteger:user.offlinemessage ] ,nil];
            
            [del.offlinemessagedic setObject:array forKey:user.name];
            
            if ([del.offlinemessagedic writeToFile:filename atomically:YES]) {
                NSLog(@"保存成功");
                
            }
        }
    }
    
    
}

-(void)hiddenkey{
    
    [self.view endEditing:YES];//取消键盘
    
    //向上移动
    [UIView animateWithDuration:0.3 delay:0 options:UIViewAnimationOptionLayoutSubviews animations:^{
        self.view.frame = CGRectMake(0, 0, 320, self.view.frame.size.height);
    } completion:^(BOOL finished) {
        NSLog(@"向上移动·");
    }];
    
}
@end



